package com.specialtreasure.freightdepot.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.app.core.activity.BaseNewActivity;
import com.app.core.config.Constants;
import com.app.core.config.HttpApi;
import com.app.core.util.UserUtils;
import com.specialtreasure.freightdepot.R;
import com.specialtreasure.freightdepot.model.Address;
import com.specialtreasure.freightdepot.model.BaseModel;
import com.specialtreasure.freightdepot.model.GoodsUser;
import com.specialtreasure.freightdepot.popupwindow.SelectCityPW;
import com.yanzhenjie.httpmodule.http.CallServer;
import com.yanzhenjie.httpmodule.http.Result;
import com.yanzhenjie.httpmodule.http.StringRequest;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.CacheMode;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.nohttp.rest.SimpleResponseListener;

import org.simple.eventbus.EventBus;

/**
 * Created by Administrator on 2017/8/25 0025.
 * 添加货主
 */

public class AddOwnerActivity extends BaseNewActivity implements View.OnClickListener {
    public static final String TAG = "AddOwnerActivity";
    boolean isSaveAdd;
    String belongProvince;//归属地省
    String belongCity;//归属地市
    String belongCounty;//归属地县

    private ImageView iv_back;
    private TextView tv_title;
    private EditText et_name;
    private EditText et_tel;
    private TextView tv_home;
    private RelativeLayout rl_home;
    private EditText et_remark;
    private Button btn_save_add;
    private Button btn_save_cancel;
    private Button btn_cancel;
    private LinearLayout ll_root;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_add_owner);
        initView();
        setData();
    }

    private void setData() {
        show(iv_back);
        tv_title.setText("添加货主");

        //监听
        et_tel.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (!b){
                    if (et_tel.getText().toString().trim().length() == 11) {
                        showDialog(Constants.LOADING);
                        checkPhone();
                    }
                }
            }
        });

    }

    private void initView() {
        iv_back = (ImageView) findViewById(R.id.iv_back);
        tv_title = (TextView) findViewById(R.id.tv_title);
        et_name = (EditText) findViewById(R.id.et_name);
        et_tel = (EditText) findViewById(R.id.et_tel);
        tv_home = (TextView) findViewById(R.id.tv_home);
        rl_home = (RelativeLayout) findViewById(R.id.rl_home);
        et_remark = (EditText) findViewById(R.id.et_remark);
        btn_save_add = (Button) findViewById(R.id.btn_save_add);
        btn_save_cancel = (Button) findViewById(R.id.btn_save_cancel);
        btn_cancel = (Button) findViewById(R.id.btn_cancel);
        ll_root = (LinearLayout) findViewById(R.id.ll_root);

        iv_back.setOnClickListener(this);
        btn_save_add.setOnClickListener(this);
        btn_save_cancel.setOnClickListener(this);
        btn_cancel.setOnClickListener(this);
        rl_home.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
            case R.id.btn_cancel:
                finish();
                break;
            case R.id.btn_save_add://保存继续添加
                isSaveAdd = false;
                submit();
                break;
            case R.id.btn_save_cancel://保存并退出
                isSaveAdd = true;
                submit();
                break;
            case R.id.rl_home://归属地
                SelectCityPW pwTo = new SelectCityPW(this);
                pwTo.showAtBottom(ll_root);
                pwTo.setOnResultListener(new SelectCityPW.OnResultListener() {
                    @Override
                    public void onResult(Address address) {
                        if (address != null) {
                            belongProvince=address.province;
                            belongCity=address.city;
                            belongCounty=address.region;
                            tv_home.setText(address.province + address.city + address.region);

                            //判断位置
                            if (address.province.equals(address.city)){
                                tv_home.setText(address.city + address.region);
                            }

                        }
                    }

                });
                break;

        }
    }

    private void submit() {
        // validate
        String phone=et_tel.getText().toString().trim();
        if (TextUtils.isEmpty(phone)){
            Toast.makeText(mContext, "请输入手机号", Toast.LENGTH_SHORT).show();
            return;
        }

        // TODO validate success, do something
        showDialog(Constants.LOADING);
        getData();
    }


    /**
     * 网络请求
     */
    private void getData() {
        String url = Constants.HTTP_URL + HttpApi.ADDGOODSUSER;
        StringRequest request = new StringRequest(url, RequestMethod.POST);
        request.add("token", UserUtils.getToken());
        request.addNull("username", et_name.getText().toString().trim());
        request.addNull("phone", et_tel.getText().toString().trim());
        request.add("remark", et_remark.getText().toString().trim());

        request.addNull("belongProvince", belongProvince);
        request.addNull("belongCity", belongCity);
        request.addNull("belongCounty", belongCounty);


        request.setCacheMode(CacheMode.ONLY_REQUEST_NETWORK);
        CallServer.getInstance().request(Constants.ZERO, request, new SimpleResponseListener<Result<String>>() {
            @Override
            public void onSucceed(int what, Response<Result<String>> response) {
                super.onSucceed(what, response);
                closeDialog();

                String result = response.get().getResult();
                Logger.e("请求成功：" + result);
                BaseModel baseModel = JSON.parseObject(result, BaseModel.class);
                if (baseModel != null) {
                    Integer status = baseModel.getStatus();
                    String msg = baseModel.getMsg();
                    if (status != null && status == 0) {
                        Toast.makeText(mContext, "添加货主成功", Toast.LENGTH_SHORT).show();
                        EventBus.getDefault().post(new BaseModel(),Constants.UPDATEOWNER);
                        EventBus.getDefault().post(new BaseModel(),Constants.UPDATEUSER);

                        if (isSaveAdd) {//保存并退出
                            finish();
                        } else {
                            clearText();
                        }

                    } else {
                        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
                    }
                }


            }
        });

    }



    /**
     * 检测我的手机号
     */
    private void checkPhone(){
        String url = Constants.HTTP_URL + HttpApi.SELECTGOODSUSERBYPHONE;
        StringRequest request = new StringRequest(url, RequestMethod.POST);
        request.add("token", UserUtils.getToken());
        request.add("phone", et_tel.getText().toString().trim());

        request.setCacheMode(CacheMode.ONLY_REQUEST_NETWORK);
        CallServer.getInstance().request(Constants.ZERO, request, new SimpleResponseListener<Result<String>>() {
            @Override
            public void onSucceed(int what, Response<Result<String>> response) {
                super.onSucceed(what, response);
                closeDialog();

                String result = response.get().getResult();
                Logger.e("请求成功：" + result);
                JSONObject jsonObject=JSON.parseObject(result);
                if (jsonObject!=null){
                    Integer status=jsonObject.getInteger("status");
                    String msg =jsonObject.getString("msg");

                    if (status != null && status == 0) {
                        GoodsUser data=JSON.parseObject(jsonObject.getJSONObject("data").toString(),GoodsUser.class);
                        if (data!=null){
                            et_name.setText(data.getName());
                            et_tel.setText(data.getPhone());
                            tv_home.setText(data.getBelongProvince()+data.getBelongCity()+data.getBelongCounty());
                        }


                    } else {
//                        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();

                    }


                }


            }
        });
    }


    /**
     * 清空文本
     */
    private void clearText() {
        et_tel.getText().clear();
        et_name.getText().clear();
        et_remark.getText().clear();

        tv_home.setText("");

    }


    @Override
    public String getActiviyName() {
        return TAG;
    }

}
